<template>
  <a-card title="平台商家信息配置">
    <a-spin :spinning="confirmLoading">
        <j-form-container :disabled="formDisabled">
          <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="门店名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shopName">
                  <a-input v-model="model.shopName" placeholder="请输入门店名称"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="门店logo" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shopLogo">
                  <j-image-upload  v-model="model.shopLogo" ></j-image-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="17" :push="4">
                  <a-tabs>
                    <a-tab-pane tab="客服信息" key="1" :forceRender="true">
                      <j-editable-table
                        ref="editableTable1"
                        :loading="table1.loading"
                        :columns="table1.columns"
                        :dataSource="table1.dataSource"
                        :maxHeight="300"
                        :rowNumber="true"
                        :rowSelection="true"
                        :actionButton="true"/>
                    </a-tab-pane>
                  </a-tabs>
              </a-col>
              <a-col :span="17" :push="8">
                <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-button type="primary" @click="handleOk">提交</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-spin>
  </a-card>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import JEditableTable from '@/components/jeecg/JEditableTable'
  import Icons from '../../../system/modules/icon/Icons.vue'
  import { FormTypes,validateTables, VALIDATE_NO_PASSED, getRefPromise, validateFormModelAndTables } from '@/utils/JEditableTableUtil'
  export default {
    name: 'YlShopConfigModal',
    components: {},
    data () {
      return {
        title:'',
        width:800,
        visible: false,
        disableSubmit: false,
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           shopName: [
              { required: true, message: '请输入门店名称!'},
           ],
           shopLogo: [
              { required: true, message: '请输入门店logo!'},
           ],
           shopCustomer: [
              { required: true, message: '请输入客服!'},
           ],
        },
        url: {
          add: "/config/ylShopConfig/add",
          edit: "/config/ylShopConfig/edit",
          queryById: "/config/ylShopConfig/queryById"
        },
         table1: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '客服名称',
              key: 'name',
              width: '24%',
              type: FormTypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '电话',
              key: 'mobile',
              width: '24%',
              type: FormTypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '企业微信链接',
              key: 'url',
              width: '24%',
              type: FormTypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            }
          ]
        },
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.getConfig();
    },
    methods: {
      getConfig(){
        getAction(this.url.queryById, {id:''}).then((res)=>{
          if (res.success) {
            this.model = res.result;
            if(this.model.shopCustomer){
              this.table1.dataSource = JSON.parse(this.model.shopCustomer);
            }
          }
        })
      },
      handleOk () {
        this.submitForm();
      },
      submitForm () {
          const that = this;
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              this.validateFields();
            }
          })
      },
      getAllTable() {
        return Promise.all([
          getRefPromise(this, 'editableTable1'),
        ])
      },
      validateFields() {
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return  validateTables(tables)
        }).then(allValues => {
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          return this.requestAddOrEdit(formData)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            console.warn('----1')
          } else {
            console.error(e)
          }
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        return {
          ...this.model, // 展开
          shopCustomer: JSON.stringify(allValues[0].values)
        }
      },
      requestAddOrEdit(formData) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if(!this.model.id){
          httpurl+=this.url.add;
          method = 'post';
        }else{
          httpurl+=this.url.edit;
            method = 'put';
        }
        // console.log("this.model",formData);
        httpAction(httpurl,formData,method).then((res)=>{
          if(res.success){
            that.$message.success(res.message);
            that.submitCallback();
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
        })
      }
    }
  }
</script>
